package com.wuda.servlet.admin;

import com.wuda.dao.UserDao;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Objects;

@WebServlet("/admin/disableOrActiveUser")
public class DisableOrActiveUser extends HttpServlet {
	private static final long serialVersionUID = 1L;


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json; charset=utf8");


		int userId = Integer.parseInt(req.getParameter("userId"));
		String status = req.getParameter("status");
//		status   ENUM ('active', 'inactive')

		System.out.println("userId:" + userId + " status:" + status);
		// 准备返回参数
		int code = 500;
		String msg = "操作失败";

		if (Objects.equals(status, "active")) {
			status = "inactive";
			msg = "禁用成功";
		} else if (Objects.equals(status, "inactive")) {
			status = "active";
			msg = "启用成功";
		}
		UserDao userDao = new UserDao();

		// 调用数据库操作方法
		boolean success = false;
		try {
			success = userDao.disableOrActiveUser(userId, status);
			if (success) {
				code = 200;
				msg = msg;
			} else {
				msg = "操作失败";
			}
			// 返回JSON结果
			JSONObject jsonResult = new JSONObject();
			jsonResult.put("code", code);
			jsonResult.put("msg", msg);

			try (PrintWriter out = resp.getWriter()) {
				out.print(jsonResult);
				out.flush();
			}


		} catch (SQLException | ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

}
